import sys

import paramiko


class SshRun:
    def __init__(self):
        pass

    @staticmethod
    def ssh_connect(ip, username, password):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, password, timeout=1800, allow_agent=False,
                    look_for_keys=False)
        return ssh

    @staticmethod
    def ssh_run(ssh, command):
        print(command)
        stdin, stdout, stderr = ssh.exec_command(command)
        run_res = stdout.read().decode('utf-8').strip()
        er_res = stderr.read().decode('utf-8').strip()
        if er_res:
            print(f'ERROR:{er_res}')
        if run_res:
            print(f'SUCCESS:{run_res}')
        return run_res

    @staticmethod
    def ssh_close(ssh):
        ssh.close()


if __name__ == '__main__':
    ip_all = ["", ""]
    pwd = sys.argv[1]
    my_sh = SshRun()
    cmd = ''
    user_prefix = ('relia',)

    # '清理内存'
    cmd += "sync;" \
           "echo 3 > /proc/sys/vm/drop_caches;"
    # 开启newpress
    cmd += "nohup /autotest_software/newpress/press_64 -c 40 " \
           "> run_press.log 2>&1 &;" \
           "pwd;"
    for i in ip_all:
        print(f'当前主机：{i}')
        conn = my_sh.ssh_connect(i, 'root', pwd)
        for c in cmd.split(';'):
            if len(c.strip()) > 0:
                my_sh.ssh_run(conn, c)
        my_sh.ssh_close(conn)
